#include "student.h"
#include <iostream>
using namespace std;


Student::Student (Printer &prt, NameServer &nameServer, WATCardOffice &cardOffice, unsigned int id, unsigned int maxPurchases) {
        this->id = id; // (1)
        numPurchases = prng(maxPurchases-1)+1; // (2-1)
        typePurchase = prng(3); // (2-2)
  this->prt = &prt;
  prt.print(Printer::Student, id, 'S', typePurchase, numPurchases);
  
        card = cardOffice.create(id,5);
        vend = nameServer.getMachine(id); // (4)
        
        // locate printer/server/office
        this->nameServer = &nameServer;
        this->cardOffice = &cardOffice;
 prt.print(Printer::Student, id, 'V', vend->getId());
}


bool Student::action() {
  if(numPurchases == 0) {
    return false;
  } else {
    VendingMachine::Status cur = vend->buy(typePurchase,card);
    if (card == NULL) {
      prt->print(Printer::Student, id, 'D');
      card = cardOffice->create(id,5);
    }
    if (cur == VendingMachine::STOCK) {
      vend = nameServer->getMachine(id);
      prt->print(Printer::Student, id, 'V', vend->getId());
      return true;
    } else if (cur == VendingMachine::FUNDS) {      
      prt->print(Printer::Student, id, 't', 3);
      cardOffice->transfer(id,3,*card);
      prt->print(Printer::Student, id, 'T', card->getFund());
      while(card->getFund() < vend->cost()) {
        prt->print(Printer::Student, id, 't', 3);
        cardOffice->transfer(id,3,*card);
        prt->print(Printer::Student, id, 'T', card->getFund());
      }
      return true;
    } else {
      numPurchases--;
      prt->print(Printer::Student, id, 'B', card->getFund());
      return true;
    }
  }
}
Student::~Student() {
  prt->print(Printer::Student, id, 'F');
}